import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { 
  Card, 
  Typography, 
  Space, 
  Tag, 
  Avatar, 
  Divider, 
  Button,
  message,
  Spin,
  Row,
  Col,
  Statistic
} from 'antd';
import {
  EyeOutlined,
  LikeOutlined,
  MessageOutlined,
  CalendarOutlined,
  UserOutlined,
  ArrowLeftOutlined,
  ShareAltOutlined
} from '@ant-design/icons';
import { getArticleAPI } from '../../apis/article';
import './ArticleView.scss';

const { Title, Paragraph, Text } = Typography;

const ArticleView = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [article, setArticle] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (id) {
      loadArticle(id);
    }
  }, [id]);

  const loadArticle = async (articleId) => {
    try {
      setLoading(true);
      const response = await getArticleAPI(articleId);
      
      if (response.success) {
        setArticle(response.data);
      } else {
        message.error(response.message || '作品不存在');
        navigate('/articles');
      }
    } catch (error) {
      console.error('加载作品失败:', error);
      message.error('加载作品失败');
      navigate('/articles');
    } finally {
      setLoading(false);
    }
  };

  const handleShare = () => {
    const url = window.location.href;
    if (navigator.share) {
      navigator.share({
        title: article.title,
        url: url
      });
    } else {
      // 复制链接到剪贴板
      navigator.clipboard.writeText(url).then(() => {
        message.success('链接已复制到剪贴板');
      });
    }
  };

  if (loading) {
    return (
      <div className="article-view-loading">
        <Spin size="large" />
      </div>
    );
  }

  if (!article) {
    return (
      <div className="article-view-error">
        <Title level={3}>作品不存在</Title>
        <Button type="primary" onClick={() => navigate('/articles')}>
          返回作品列表
        </Button>
      </div>
    );
  }

  return (
    <div className="article-view">
      <div className="article-view-container">
        {/* 返回按钮 */}
        <div className="article-view-header">
          <Button 
            icon={<ArrowLeftOutlined />} 
            onClick={() => navigate('/articles')}
          >
            返回列表
          </Button>
          <Button 
            icon={<ShareAltOutlined />} 
            onClick={handleShare}
          >
            分享
          </Button>
        </div>

        {/* 作品内容 */}
        <Card className="article-content-card">
          {/* 作品标题 */}
          <div className="article-header">
            <Title level={1} className="article-title">
              {article.title}
            </Title>
            
            {/* 作品元信息 */}
            <div className="article-meta">
              <Space size="large" wrap>
                <Space>
                  <Avatar 
                    src={article.avatar_url} 
                    icon={<UserOutlined />} 
                    size="small"
                  />
                  <Text>{article.username || '匿名用户'}</Text>
                </Space>
                
                <Space>
                  <CalendarOutlined />
                  <Text type="secondary">
                    {new Date(article.created_at).toLocaleDateString('zh-CN', {
                      year: 'numeric',
                      month: 'long',
                      day: 'numeric'
                    })}
                  </Text>
                </Space>

                <Tag color={article.status === 'published' ? 'green' : 'orange'}>
                  {article.status === 'published' ? '已发布' : '草稿'}
                </Tag>
              </Space>
            </div>

            {/* 统计信息 */}
            <Row gutter={16} className="article-stats">
              <Col span={8}>
                <Statistic
                  title="阅读量"
                  value={article.view_count || 0}
                  prefix={<EyeOutlined />}
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="点赞数"
                  value={article.like_count || 0}
                  prefix={<LikeOutlined />}
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="评论数"
                  value={article.comment_count || 0}
                  prefix={<MessageOutlined />}
                />
              </Col>
            </Row>
          </div>

          <Divider />

          {/* 封面图片 */}
          {article.cover_image && (
            <div className="article-cover">
              <img 
                src={article.cover_image} 
                alt={article.title}
                className="cover-image"
              />
            </div>
          )}

          {/* 作品正文 */}
          <div className="article-body">
            <div 
              className="article-content"
              dangerouslySetInnerHTML={{ 
                __html: article.content_html || '<p>暂无内容</p>' 
              }}
            />
          </div>

          <Divider />

          {/* 作品底部信息 */}
          <div className="article-footer">
            <Space>
              <Text type="secondary">
                发布于 {new Date(article.created_at).toLocaleString('zh-CN')}
              </Text>
              {article.updated_at !== article.created_at && (
                <Text type="secondary">
                  · 更新于 {new Date(article.updated_at).toLocaleString('zh-CN')}
                </Text>
              )}
            </Space>
          </div>
        </Card>

        {/* 相关操作 */}
        <Card className="article-actions">
          <Space size="large">
            <Button 
              type="primary" 
              icon={<LikeOutlined />}
              size="large"
            >
              点赞 ({article.like_count || 0})
            </Button>
            <Button 
              icon={<MessageOutlined />}
              size="large"
            >
              评论 ({article.comment_count || 0})
            </Button>
            <Button 
              icon={<ShareAltOutlined />}
              size="large"
              onClick={handleShare}
            >
              分享
            </Button>
          </Space>
        </Card>
      </div>
    </div>
  );
};

export default ArticleView;